package com.py.credit.controller;

import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.LhjcConstants;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.WebServiceResultObj;
import com.py.credit.service.FeedbackService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.OfficeService;
import com.py.credit.service.SubjectCenterInterface;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.XmlUtil;
import com.py.framework.core.helper.JWTHelper;
import net.sf.json.xml.XMLSerializer;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.*;

/**
 * 共享数据获取及反馈
 */
@Controller
@RequestMapping(value = "/subjectCenter")
public class SubjectCenterController {

    @Autowired
    private SubjectCenterInterface subjectCenterInterface;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private FeedbackService feedbackService;

    /**
     * 获取详情数据
     *
     * @return
     */
//    @RequestMapping(value = "/detail.json")
//    public ModelAndView getDetail(@RequestParam(value = "sign", defaultValue = "", required = true) String sign,
//                                  @RequestParam(value = "qymc", defaultValue = "", required = true) String qymc,
//                                  @RequestParam(value = "username", defaultValue = "", required = true) String username) {
//        Map<String, Object> map = new HashMap<String, Object>();
//
//        //校验签名是否正确
//        if (!sign.equals(XmlUtil.SIGN)) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "签名不正确");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        }
//
//        //校验用户名是否为空
//        if (username.equals("")) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "用户名为空");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        }
//
//        //企业名称是否为空
//        if (qymc.equals("")) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "企业名称为空");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        }
//
//        //校验用户名是否存在
//        SysUser manager = lhjcRemoteBaseService.getByUsername(username);
//        if (null == manager || null == manager.getUsername() || "".equals(manager.getUsername())) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "该用户不存在");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        }
//
//        try {
//            //调用webService接口
//            ShareDataInterfaceService port = service.getShareDataInterfaceServiceImplPort();
//            String xml = port.getSubject(XmlUtil.KEY, qymc, "", "", "", "");
//
//            //用xml工具类解析xml
//            JSONObject companyInfo = XmlUtil.xml2JSON(xml.getBytes("UTF-8"));
//            Map<String, List<String>> result = (Map<String, List<String>>) companyInfo.get("result");
//            if (null != result.get("success") && result.get("success").get(0).equals("false")) {
//                map.put("code", WebServiceResultObj.CODE_FAIL);
//                map.put("msg", result.get("info").get(0));
//                return new ModelAndView("/webService/subjectCenter/error", map);
//            }
//
//            if (result.get("hongmdsl").get(0).equals("0") && result.get("heimdsl").get(0).equals("0")) {
//                map.put("code", WebServiceResultObj.CODE_FAIL);
//                map.put("msg", "该企业无红明单和黑名单数据");
//                return new ModelAndView("/webService/subjectCenter/error", map);
//            }
//
//            //查询详情
//            String detail = port.getSubjectDetail(XmlUtil.KEY, result.get("id").get(0));
//            JSONObject detailInfo = XmlUtil.xml2JSON(detail.getBytes("UTF-8"));
//            Map<String, List<Object>> credit = (Map<String, List<Object>>) detailInfo.get("credit");
//            if (null == credit) {
//                map.put("code", WebServiceResultObj.CODE_FAIL);
//                map.put("msg", "主体不存在");
//                return new ModelAndView("/webService/subjectCenter/error", map);
//            }
//
//            // 缓存用户会话信息
//            String lhjcToken = JWTHelper.createJWT(String.valueOf(manager.getId()), manager.getUsername(), LhjcConstants.NUMBER_ZERO);
//            subjectCenterInterface.putUserSessionData(lhjcToken, manager);
//
//            String deptId = officeService.selectTopDeptId(manager.getOfficeId() + "");
//            Map<String, Object> data = subjectCenterInterface.getFeedbackData(result, credit, Long.parseLong(deptId), username, manager.getId(), manager, lhjcToken);
//
//            // 清除用户会话信息
//            subjectCenterInterface.clearUserSessionData(lhjcToken);
//
//            return new ModelAndView("/webService/subjectCenter/main", data);
//        } catch (JDOMException e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "查询失败");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        } catch (IOException e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "查询失败");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        } catch (Exception e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "查询失败");
//            return new ModelAndView("/webService/subjectCenter/error", map);
//        }
//    }

    /**
     * 奖惩反馈
     *
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "/feedback.json")
//    public Object jcFeedback(@RequestParam(value = "id", defaultValue = "", required = true) String id,
//                             @RequestParam(value = "username", defaultValue = "", required = true) String username,
//                             @RequestParam(value = "objname", defaultValue = "", required = true) String objname,
//                             @RequestParam(value = "objtype", defaultValue = "", required = true) String objtype,
//                             @RequestParam(value = "creditcode", defaultValue = "", required = true) String creditcode,
//                             @RequestParam(value = "executedt", defaultValue = "", required = true) String executedt,
//                             @RequestParam(value = "executeunit", defaultValue = "", required = true) String executeunit,
//                             @RequestParam(value = "accordingto", defaultValue = "", required = true) String accordingto,
//                             @RequestParam(value = "measurename", defaultValue = "", required = true) String measurename,
//                             @RequestParam(value = "matter", defaultValue = "", required = true) String matter,
//                             @RequestParam(value = "content", defaultValue = "", required = true) String content,
//                             @RequestParam(value = "money", defaultValue = "", required = true) String money,
//                             @RequestParam(value = "backtype", defaultValue = "", required = true) String backtype,
//                             @RequestParam(value = "result", defaultValue = "", required = true) String result,
//                             @RequestParam(value = "remark", defaultValue = "", required = true) String remark) {
//        Map<String, Object> map = new HashMap<String, Object>();
//
//        //调用webService接口
//        ShareDataInterfaceService port = service.getShareDataInterfaceServiceImplPort();
//        net.sf.json.JSONObject data = new net.sf.json.JSONObject();
//        data.put("objname", objname);
//        data.put("objtype", objtype);
//        data.put("creditcode", creditcode);
//
//        data.put("executedt", executedt);
//        data.put("executeunit", executeunit);
//        data.put("accordingto", accordingto);
//
//        String cs = "";
//        String[] arr = measurename.split("_");
//        for (int i = 0; i < arr.length; i++) {
//            cs = cs + arr[i].split("-")[1] + ",";
//        }
//        cs = cs.substring(0, cs.length() - 1);
//
//        data.put("measurename", cs);
//        data.put("matter", matter);
//        data.put("content", content);
//        data.put("money", money);
//        data.put("backtype", backtype);
//        data.put("result", result);
//        data.put("remark", remark);
//        XMLSerializer xmlSerializer = new XMLSerializer();
//        xmlSerializer.setRootName("feedback");
//        xmlSerializer.setTypeHintsEnabled(false);
//        String xml = xmlSerializer.write(data);
//        String res = port.setFeedback(XmlUtil.KEY, id, xml);
//        //用xml工具类解析xml
//        JSONObject feedbackInfo = null;
//        try {
//            feedbackInfo = XmlUtil.xml2JSON(res.getBytes("UTF-8"));
//
//            Map<String, List<String>> resultMap = (Map<String, List<String>>) feedbackInfo.get("result");
//            if (null != resultMap.get("success") && resultMap.get("success").get(0).equals("true")) {
//                map.put("code", WebServiceResultObj.CODE_SUCCESS);
//                SysUser manager = lhjcRemoteBaseService.getByUsername(username);
//
//                // 缓存用户会话信息
//                String lhjcToken = JWTHelper.createJWT(String.valueOf(manager.getId()), manager.getUsername(), LhjcConstants.NUMBER_ZERO);
//                subjectCenterInterface.putUserSessionData(lhjcToken, manager);
//
//                Map<String, Set<String>> ajbhMap = this.getAjbhMap(arr);
//                for (Map.Entry<String, Set<String>> entry : ajbhMap.entrySet()
//                        ) {
//                    feedbackService.addFeedback(entry.getKey(), DateUtil.getInstance().dateToStr(DateUtil.getInstance().getMinuteDate(executedt, DateUtil.YYYY_MM_DD), DateUtil.YYYY_MM_DD_HH_MM_SS), content, subjectCenterInterface.getCfbmByAjbh(entry.getKey()) + "", new ArrayList<String>(entry.getValue()), manager, lhjcToken);
//                }
//
//                // 清除用户会话信息
//                subjectCenterInterface.clearUserSessionData(lhjcToken);
//            } else {
//                map.put("code", WebServiceResultObj.CODE_FAIL);
//            }
//            map.put("msg", resultMap.get("info").get(0));
//        } catch (JDOMException e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "反馈失败");
//        } catch (IOException e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "反馈失败");
//        } catch (Exception e) {
//            map.put("code", WebServiceResultObj.CODE_FAIL);
//            map.put("msg", "反馈失败");
//        }
//
//        return map;
//    }

    private Map<String, Set<String>> getAjbhMap(String arr[]) {
        Map<String, Set<String>> ajbhMap = new HashMap<String, Set<String>>();

        for (int i = 0; i < arr.length; i++) {
            String[] value = arr[i].split("-");
            List<String> ajbhList = Arrays.asList(value[2].split(","));
            for (String ajbh : ajbhList
                    ) {
                if (ajbhMap.containsKey(ajbh)) {
                    ajbhMap.get(ajbh).add(value[0]);
                } else {
                    Set<String> csSet = new HashSet<String>();
                    csSet.add(value[0]);
                    ajbhMap.put(ajbh, csSet);
                }
            }
        }

        return ajbhMap;
    }
}
